package com.vichat.task;

import com.alibaba.dubbo.container.spring.SpringContainer;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.signal.CmdUtil;
import com.vichat.common.vo.PageFilter;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.entity.RoomMember;
import com.vichat.room.service.IRoomService;
import com.vichat.task.service.ITask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by ranjx on 2018/06/29.
 * 获取过期频道，执行频率凌晨03：00
 */
@Component("ExpireRoomTask")
public class ExpireRoomTask implements ITask {
    private static transient final Logger logger = LoggerFactory.getLogger(ExpireRoomTask.class);
    private IRoomService roomService;
    private long rid;

    @Override
    public String doTask(long cfgTaskId) throws Exception {
        ApplicationContext ctx = SpringContainer.getContext();
        roomService = (IRoomService) ctx.getBean("roomService", IRoomService.class);
        List<RoomBasic> roomBasics = roomService.queryExpireRoom();
        if (!roomBasics.isEmpty()) {
            for (RoomBasic val : roomBasics) {
                logger.info("删除过期临时表:" + val.getName() + ",编号:" + val.getRid());
                rid = val.getRid();
                roomService.delRoomBasic(val);
                roomService.updateRoomBasicVersion(val.getRid());
                this.flushMsg();
            }
        }
        return null;
    }

    public void flushMsg() {
        try {
            RoomMember queryBean = new RoomMember();
            queryBean.setRid(rid);
            List<RoomMember> roomMembers = roomService.queryRoomMemers(queryBean, PageFilter.getMaxPageFilter());
            if (!roomMembers.isEmpty()) {
//                roomService.delUselessMembers(rid);
                for (RoomMember member : roomMembers) {
                    CmdUtil.sendImMsg(10000, member.getUid(), rid, GlobalConstant.IMS_MSG_TYPE_10009, "");
                }
            }
            CmdUtil.sendRoomMsg(10000, 0, rid, GlobalConstant.GMS_MSG_TYPE_10009, "");
        } catch (Exception e) {
            logger.error("发送消息失败>>>>>>" + e.getMessage(), e);
        }
    }
}
